package com.chapter.sample.redis.answer;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class HyperLogLogService {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 模拟后台用户点击首页，每个用户来自不同的IP地址
     */
    @PostConstruct
    public void init() {

        new Thread(() -> {
            String ip = null;

            for (int i = 0; i <= 200; i++) {
                Random random = new Random();
                ip = random.nextInt(256) + "." + random.nextInt(256) + "." + random.nextInt(256) + "." + random.nextInt(256);
                Long hll = redisTemplate.opsForHyperLogLog().add("hll", ip);
                log.info("ip=「{}」,该IP地址访问首页的次数=「{}」", ip, hll);

                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    public Long uv() {
        return redisTemplate.opsForHyperLogLog().size("hll");
    }
}
